import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import api from '../utils/api';
import { RequestError } from '../utils/request';
import { uploadCaseImage, deleteCaseImages } from '../utils/oss';
import { userStorage } from '../utils/storage';
import UploadDialog from '../components/UploadDialog';
import './EditCase.css';

function EditCase() {
  const navigate = useNavigate();
  const { caseId } = useParams(); // 从URL参数获取caseId
  
  // 案例数据
  const [caseData, setCaseData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  // 表单数据
  const [caseTitle, setCaseTitle] = useState('');
  const [caseContent, setCaseContent] = useState('');
  const [caseType, setCaseType] = useState('emotion'); // 'emotion' | 'money' | 'study'
  const [caseImages, setCaseImages] = useState([]); // 存储原始图片URL（只读）
  const [ossImages, setOssImages] = useState([]); // 存储OSS图片路径（用于保存）
  const [newImages, setNewImages] = useState([]); // 存储新上传的图片文件对象和预览URL
  const [isReuploading, setIsReuploading] = useState(false); // 是否正在重新上传图片
  
  // 上传进度状态
  const [uploadDialogVisible, setUploadDialogVisible] = useState(false);
  const [currentTask, setCurrentTask] = useState('');
  const [taskProgress, setTaskProgress] = useState(0);
  const [totalTasks, setTotalTasks] = useState(0);
  const [completedTasks, setCompletedTasks] = useState(0);
  const [uploadPhase, setUploadPhase] = useState('idle'); // idle | uploading | uploaded | updating | success | error

  // 获取案例详情
  useEffect(() => {
    if (!caseId) {
      alert('缺少案例ID参数');
      navigate('/main/case');
      return;
    }
    
    fetchCaseDetail(caseId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [caseId]);

  const fetchCaseDetail = async (caseId) => {
    try {
      setLoading(true);
      setError(null);

      console.log('查询案例详情，caseId:', caseId);
      const result = await api.case.getCaseById(caseId);
      
      console.log('案例详情结果:', result);

      if (result) {
        setCaseData(result);
        setCaseTitle(result.caseTitle || '');
        setCaseContent(result.caseContent || '');
        setCaseType(result.caseType || 'emotion');
        setCaseImages(result.caseImages || []);
        setOssImages(result.ossImages || []);
        setNewImages([]); // 重置新图片
        setIsReuploading(false); // 重置重新上传状态
      }
    } catch (error) {
      console.error('获取案例详情失败:', error);
      if (error instanceof RequestError) {
        setError(error.message);
      } else {
        setError('获取案例详情失败，请重试');
      }
    } finally {
      setLoading(false);
    }
  };

  // 处理重新上传图片
  const handleReuploadImages = () => {
    // 创建隐藏的文件输入元素
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.multiple = true;
    input.onchange = (e) => {
      const files = Array.from(e.target.files);
      
      if (files.length === 0) {
        return;
      }
      
      if (files.length > 9) {
        alert('最多只能上传9张图片');
        return;
      }

      const validImages = [];
      for (let file of files) {
        if (!file.type.startsWith('image/')) {
          alert(`${file.name} 不是图片文件，已跳过`);
          continue;
        }
        
        // 创建预览URL
        const previewUrl = URL.createObjectURL(file);
        validImages.push({
          file: file,
          previewUrl: previewUrl,
          name: file.name
        });
      }
      
      if (validImages.length > 0) {
        // 释放之前新图片的预览URL
        newImages.forEach(image => {
          if (image.previewUrl) {
            URL.revokeObjectURL(image.previewUrl);
          }
        });
        
        setNewImages(validImages);
        setIsReuploading(true); // 标记为重新上传状态
      }
    };
    input.click();
  };

  // 删除新上传的图片
  const handleRemoveNewImage = (index) => {
    const imageToRemove = newImages[index];
    // 释放预览URL
    if (imageToRemove.previewUrl) {
      URL.revokeObjectURL(imageToRemove.previewUrl);
    }
    
    const newImageList = newImages.filter((_, i) => i !== index);
    setNewImages(newImageList);
    
    // 如果删除了所有新图片，恢复显示原始图片
    if (newImageList.length === 0) {
      setIsReuploading(false);
    }
  };

  // 处理保存
  const handleSave = async () => {
    // 表单验证
    if (!caseTitle.trim()) {
      alert('请输入案例标题');
      return;
    }
    if (!caseContent.trim()) {
      alert('请输入案例正文');
      return;
    }

    // 如果没有重新上传图片，且原始图片为空，提示用户
    if (!isReuploading && caseImages.length === 0) {
      alert('请至少上传一张图片');
      return;
    }

    // 如果重新上传了图片，验证新图片
    if (isReuploading && newImages.length === 0) {
      alert('请至少上传一张图片');
      return;
    }

    setUploadDialogVisible(true);
    setUploadPhase('uploading');

    // 在try外部定义变量，以便在catch中使用
    let imagePaths = [];
    let imagesUploaded = false;
    let teacherPhone = '';
    let timestamp = '';

    try {
      // 1. 获取用户信息
      const userInfo = userStorage.getUserInfo();
      if (!userInfo || !userInfo.phone) {
        setUploadDialogVisible(false);
        alert('未获取到用户信息，请重新登录');
        navigate('/login');
        return;
      }

      teacherPhone = userInfo.phone;

      // 2. 如果重新上传了图片，需要先删除旧图片，然后上传新图片
      if (isReuploading && newImages.length > 0) {
        // 2.1 删除旧图片
        if (caseImages && caseImages.length > 0) {
          setCurrentTask('正在删除旧图片...');
          setTaskProgress(0);
          
          try {
            await deleteCaseImages(caseImages);
            console.log('旧图片删除成功');
          } catch (error) {
            console.error('删除旧图片失败:', error);
            // 继续执行，不中断流程
          }
        }

        // 2.2 上传新图片
        timestamp = Date.now().toString(); // 使用时间戳作为目录名
        setTotalTasks(newImages.length);
        setCompletedTasks(0);
        imagePaths = [];
        
        console.log('开始上传新案例图片...');
        
        for (let i = 0; i < newImages.length; i++) {
          const image = newImages[i];
          const imageIndex = i + 1; // pic1, pic2, ...
          
          setCurrentTask(`图片 ${imageIndex} 上传中`);
          setTaskProgress(0);
          
          const ossPath = await uploadCaseImage(
            image.file,
            teacherPhone,
            timestamp,
            imageIndex,
            (progress) => {
              // progress 是 0-1 之间的值，转换为百分比
              const percentage = typeof progress === 'number' ? progress * 100 : 0;
              setTaskProgress(percentage);
              console.log(`图片 ${imageIndex} 上传进度:`, percentage + '%');
            }
          );
          imagePaths.push(ossPath);
          setCompletedTasks(i + 1);
          console.log(`图片 ${imageIndex} 上传成功:`, ossPath);
        }

        imagesUploaded = true;
        setUploadPhase('uploaded');
        setCurrentTask('图片上传完成，正在保存案例信息...');
        console.log('所有新图片上传成功:', imagePaths);
      } else {
        // 3. 如果没有重新上传图片，使用原始图片路径
        imagePaths = ossImages || [];
      }

      // 4. 调用编辑接口
      setUploadPhase('updating');
      setCurrentTask('保存案例信息中...');
      console.log('准备编辑案例，参数:', {
        caseId: caseData._id,
        caseTitle: caseTitle.trim(),
        caseContent: caseContent.trim(),
        caseImages: imagePaths
      });

      const result = await api.case.editCaseById(
        caseData._id,
        caseTitle.trim(),
        caseContent.trim(),
        imagePaths
      );

      console.log('案例编辑成功:', result);

      // 5. 清理新图片的预览URL，释放内存
      newImages.forEach(image => {
        if (image.previewUrl) {
          URL.revokeObjectURL(image.previewUrl);
        }
      });

      setUploadPhase('success');
      setUploadDialogVisible(false);

      // 6. 提示成功并返回案例管理页面
      alert('案例编辑成功！');
      navigate('/main/case');

    } catch (error) {
      console.error('编辑案例失败:', error);
      
      // 如果图片已全部上传成功但接口调用失败，允许重试
      if (imagesUploaded && imagePaths.length > 0) {
        setUploadPhase('error');
        if (error instanceof RequestError) {
          setCurrentTask(`保存失败: ${error.message} - 图片已上传，可以重试`);
        } else {
          setCurrentTask(`保存失败: ${error.message || '未知错误'} - 图片已上传，可以重试`);
        }
      } else {
        // 图片上传失败或接口调用失败，关闭对话框并提示
        setUploadDialogVisible(false);
        if (error instanceof RequestError) {
          alert(`编辑失败: ${error.message}`);
        } else {
          alert(`编辑失败: ${error.message || '请重试'}`);
        }
      }
    }
  };

  // 重试保存案例信息
  const handleRetry = async () => {
    // 重新调用保存逻辑
    await handleSave();
  };

  // 取消上传（关闭对话框）
  const handleCancelUpload = () => {
    setUploadDialogVisible(false);
    setUploadPhase('idle');
    // 注意：已上传的图片不会删除，用户需要手动处理
  };

  if (loading) {
    return (
      <div className="edit-case-container">
        <div className="edit-case-box">
          <div className="loading-container">
            <div className="loading-spinner"></div>
            <p>加载中...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="edit-case-container">
        <div className="edit-case-box">
          <div className="error-container">
            <p className="error-message">❌ {error}</p>
            <button className="retry-btn" onClick={() => fetchCaseDetail(caseId)}>
              重试
            </button>
            <button className="back-btn" onClick={() => navigate('/main/case')}>
              返回案例管理
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="edit-case-container">
      <div className="edit-case-box">
        <h2>编辑案例</h2>
        
        <div className="form-section">
          {/* 图片展示区域 */}
          <div className="form-group">
            <label>案例图片</label>
            <div className="image-display-grid">
              {isReuploading ? (
                // 重新上传模式：只显示新图片
                newImages.length > 0 ? (
                  newImages.map((image, index) => (
                    <div key={index} className="image-item">
                      <img src={image.previewUrl} alt={`新图片 ${index + 1}`} />
                      <button
                        type="button"
                        className="remove-image-btn"
                        onClick={() => handleRemoveNewImage(index)}
                        title="删除图片"
                      >
                        ×
                      </button>
                    </div>
                  ))
                ) : (
                  <div className="no-images">暂无图片</div>
                )
              ) : (
                // 正常模式：显示原始图片
                caseImages.length > 0 ? (
                  caseImages.map((imageUrl, index) => (
                    <div key={index} className="image-item readonly">
                      <img src={imageUrl} alt={`案例图片 ${index + 1}`} />
                    </div>
                  ))
                ) : (
                  <div className="no-images">暂无图片</div>
                )
              )}
              
              {/* 如果重新上传模式且未满9张，显示添加图片按钮 */}
              {isReuploading && newImages.length < 9 && (
                <div className="image-item add-image-item">
                  <input
                    type="file"
                    id="image-upload-edit"
                    accept="image/*"
                    multiple
                    onChange={(e) => {
                      const files = Array.from(e.target.files);
                      const remainingSlots = 9 - newImages.length;
                      
                      if (files.length > remainingSlots) {
                        alert(`最多只能上传9张图片，当前已有${newImages.length}张，还可以上传${remainingSlots}张`);
                        e.target.value = '';
                        return;
                      }

                      const validImages = [];
                      for (let file of files) {
                        if (!file.type.startsWith('image/')) {
                          alert(`${file.name} 不是图片文件，已跳过`);
                          continue;
                        }
                        
                        const previewUrl = URL.createObjectURL(file);
                        validImages.push({
                          file: file,
                          previewUrl: previewUrl,
                          name: file.name
                        });
                      }
                      
                      setNewImages([...newImages, ...validImages]);
                      e.target.value = '';
                    }}
                    style={{ display: 'none' }}
                  />
                  <label htmlFor="image-upload-edit" className="add-image-btn">
                    <span className="add-icon">+</span>
                    <span className="add-text">添加图片</span>
                  </label>
                </div>
              )}
            </div>
            <button
              type="button"
              className="reupload-btn"
              onClick={handleReuploadImages}
            >
              {isReuploading ? '重新选择图片' : '重新上传图片'}
            </button>
            {isReuploading && (
              <div className="upload-tip">
                最多可上传9张图片，支持 JPG、PNG 格式，单张大小不超过 5MB
              </div>
            )}
          </div>

          {/* 标题输入 */}
          <div className="form-group">
            <label className="required">案例标题</label>
            <input
              type="text"
              value={caseTitle}
              onChange={(e) => setCaseTitle(e.target.value)}
              placeholder="请输入案例标题"
              maxLength="20"
            />
            <div className="char-count">
              {caseTitle.length} / 20
            </div>
          </div>

          {/* 类型选择 */}
          <div className="form-group">
            <label className="required">案例类型</label>
            <div className="radio-group">
              <label className="radio-item">
                <input
                  key={`caseType-emotion-${caseType}`}
                  type="radio"
                  name="caseType"
                  value="emotion"
                  checked={caseType === 'emotion'}
                  onChange={(e) => setCaseType(e.target.value)}
                />
                <span>情感</span>
              </label>
              <label className="radio-item">
                <input
                  key={`caseType-money-${caseType}`}
                  type="radio"
                  name="caseType"
                  value="money"
                  checked={caseType === 'money'}
                  onChange={(e) => setCaseType(e.target.value)}
                />
                <span>金钱</span>
              </label>
              <label className="radio-item">
                <input
                  key={`caseType-study-${caseType}`}
                  type="radio"
                  name="caseType"
                  value="study"
                  checked={caseType === 'study'}
                  onChange={(e) => setCaseType(e.target.value)}
                />
                <span>学业</span>
              </label>
            </div>
          </div>

          {/* 正文输入 */}
          <div className="form-group">
            <label className="required">案例正文</label>
            <textarea
              value={caseContent}
              onChange={(e) => setCaseContent(e.target.value)}
              placeholder="请输入案例正文内容"
              rows="10"
              maxLength="5000"
            />
          </div>
        </div>
      </div>

      {/* 底部固定按钮 */}
      <div className="fixed-footer">
        <div className="footer-content">
          <button
            type="button"
            className="cancel-btn"
            onClick={() => navigate('/main/case')}
            disabled={uploadPhase === 'uploading' || uploadPhase === 'updating'}
          >
            取消
          </button>
          <button
            type="button"
            className="save-btn"
            onClick={handleSave}
            disabled={uploadPhase === 'uploading' || uploadPhase === 'updating'}
          >
            {uploadPhase === 'uploading' || uploadPhase === 'updating' ? '保存中...' : '保存'}
          </button>
        </div>
      </div>

      {/* 上传进度对话框 */}
      <UploadDialog
        visible={uploadDialogVisible}
        currentTask={currentTask}
        progress={taskProgress}
        totalTasks={totalTasks}
        completedTasks={completedTasks}
        phase={uploadPhase}
        onRetry={handleRetry}
        onCancel={handleCancelUpload}
      />
    </div>
  );
}

export default EditCase;

